//创建用户仓库
import { store } from "@/store";
import { defineStore } from "pinia";
import * as api from "@/api/auth";

//定义用户仓库
export const userStore = defineStore("user", {
	//定义仓库名称
	//定义数据源
	state: () => ({
		//用户信息
		user: null,
		//是否登录
		login: false,
		code: "",
		codeStatus: "loading",
		timer: null,
		loginStatus: 801,
		cookie: "",
		other: false,
	}),
	//定义方法
	actions: {
		//二维码登录
		async loginByQrCode() {
			//获取二维码key
			const res = await api.getQrKey();
			if (res.code == 200) {
				const rec = await api.getQrCode(res.unikey);
				if (rec.code == 200) {
					this.code = rec.data.qrurl;
					this.codeStatus = "active";
					// 二维码轮询
					if (this.timer != null) {
						clearInterval(this.timer);
						this.timer = setInterval(async () => {
							await api.checkQrCode(res.unikey).then((rea) => {
								this.loginStatus = rea.code;
								if (rea.code == 803) {
									this.cookie = rea.cookie;
									api.getUserInfo();
									this.isLogin();
									clearInterval(this.timer);
								} else if (rea.code == 800) {
									clearInterval(this.timer);
									this.codeStatus = "expired";
								}
							});
						}, 2000);
					} else {
						this.timer = setInterval(async () => {
							await api.checkQrCode(res.unikey).then((rea) => {
								this.loginStatus = rea.code;
								switch (rea.code) {
									case 800:
										clearInterval(this.timer);
										this.codeStatus = "expired";
										break;
									case 803:
										this.cookie = rea.cookie;
										api.getUserInfo();
										this.isLogin();
										clearInterval(this.timer);
								}
							});
						}, 2000);
					}
				} else {
					this.codeStatus = "expired";
				}
			}
		},
		//关闭二维码登录轮询
		async closeQrCode() {
			clearInterval(this.timer);
		},
		async getUserInfo() {
			const res = await api.getUserInfo();
			console.log(res);
			// if (res.code == 200) {
			// 	this.user = res.profile;
			// 	this.login = true;
			// }
		},
		//登录
		async isLogin() {
			//调用登录接口
			const res = await api.isLogin();
			//判断是否登录成功
			if (res.code === 200) {
				//设置用户信息
				this.user = res.profile;
				//设置登录状态
				if (res.profile != null) {
					this.login = true;
				}
			}
			//返回结果
			return res;
		},
		//退出登录
	},
});
export function useUserStoreWithOut() {
	return userStore(store);
}
